import TableTpl from "./edit-table.html";
import TdTpl from "./td.html";

import "./edit-table.scss";

module.exports = function(wrap, tableId, options, cbk) {
    options = $.extend({
        header: []
    }, options);

    let $table = null, $tBody = null;
    let cache = options.init || [];
    $(wrap).each(function() {
        const $this = $(this);
        $this.html(TableTpl({tHeader: options.tHeader, tableId: tableId, noEdit: options.noEdit}));
        $table = $(`#${tableId}`), $tBody = $table.find('tbody');
        cache.forEach(item => {
            options.tHeader.forEach(header=>{
                header.val = item[header.name];
            })
            add(true);
        });
    })
    .addClass('ts-table-ctt-parent')
    .on('click', '.js-save', function() {
        const $this = $(this), $tr = $this.parents('tr'), $inputs = $tr.find('input'), idx = $tr.index();
        
        let inpusVal = {}, save = true ;
        $inputs.each(function() {
            const $input = $(this), val = this.value, 
                  name = this.name, reg = $input.data('reg');

            if(/^\s*$/.test(val) && !$input.hasClass('js-auto-fill')) {
                save = false;
                $input.addClass('error');
            }else if(reg && !(new RegExp(reg).test(val)) ) {
                save = false;                
                $input.addClass('error');
            } else {
                if(name) {
                    inpusVal[name] = val;
                }
                $input.removeClass('error');
            }
        });
        if(save) {
            $tr.data('isSave', true);
            $tr.find('.iconfont').addClass('hide');
            $inputs.attr('readonly', true).addClass('readyonly').attr('type', 'hidden').siblings('span').removeClass('hide');
            $inputs.each(function() {
                $(this).siblings('span').text(this.value)
            });
            $this.addClass('hide').siblings('.js-edit').removeClass('hide');
            cache[idx] = inpusVal;
        }
    })
    .on('click', '.js-edit', function() {
        const $tr = $(this).parents('tr');
        $(this).addClass('hide').siblings('.js-save').removeClass('hide').parents('tr').find('input').removeClass('readyonly').attr('type', 'text').siblings('span').addClass('hide').end().not('.js-select,.js-auto-fill,.js-ready-only').attr('readonly', false);
        $tr.data('isSave', false).find('.iconfont').removeClass('hide');
    })
    .on('click', '.js-remove', function() {
        const $this = $(this), $tr = $this.parents('tr'), idx = $tr.index();
        $tr.remove();
        $table.find('tbody tr:even').addClass('ts-table-odd').end().find('tbody tr:odd').removeClass('ts-table-odd');
        cache.splice(idx, 1);        
    })
    .on('click', '.js-select', function() {
        const $this = $(this), idx = $this.data('idx'), selectFillName = $this.data('fillname'), 
              tHeader = options.tHeader, $autoFills = $('.js-auto-fill'), $tr = $this.parents('tr');
              
            if($tr.data('isSave')) {
                return;
            }
            tHeader[idx].select(function(selected){
                $this.val(selected[selectFillName]);
                $autoFills.each(function(){
                    const $innerThis = $(this), fillname = $innerThis.data('fillname');
                    $innerThis.val(selected[fillname]);
                });
                if(typeof options.selected === 'function') {
                    options.selected($tr, selected);
                }
            })
    })
    .on('click', '.icon-shanchu', function() {
        const $this = $(this), $tr = $this.parents('tr');
        $tr.find(".js-select,.js-auto-fill").val('');
        if(typeof options.selected === 'function') {
            options.selected($tr);
        }
    });
    
    if(cbk) {
        cbk();
    }   

    /**
     * 添加
     */
    function add(init) {
        $tBody.append(TdTpl({
            td: options.tHeader,
            idx: $tBody.find('tr').length,
            init
        }));

        if(typeof options.callback === 'function') {
            options.callback();
        }
    }

    const exportsFun = {
        add: function() {
            add();
            return this;
        },
        getList() {            
            return cache;
        }
    }
    return exportsFun;
}